# -*- coding: utf-8 -*-
# Create time: 2020-03-11 22:33
# Author:Rongzhikai
from requests.utils import cookiejar_from_dict, dict_from_cookiejar
import requests


class Run_api:
    def __init__(self):
        self.session = requests.session()
        self.session.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36 Edg/90.0.818.56'
        }
        self.res = ''

    # 更新会话session的header和cookies
    def updateSession(self, headers=None, cookies=None):
        # 更新头信息
        if headers is not None:
            self.session.headers.update(headers)  # 将参数中的headers更新到session的headers
        # 更新cookies
        if cookies is not None:
            dict_temp = dict_from_cookiejar(self.session.cookies)  # 转化当前的cookies为dict
            dict_cookie = {**dict_temp, **cookies}  # 将当前的cookies与参数的cookies合并
            self.session.cookies = cookiejar_from_dict(dict_cookie)  # 将合并后的cookies字典转化为session的cookies

    # 发送请求，判断再次发什么类型的请求
    def send_api(self, method, url, **kwargs):
        self.res = self.session.request(method, url, **kwargs)
        return self.res.status_code, self.res.content.decode('utf-8')

    def close_all(self):
        self.session.close()


if __name__ == '__main__':
    url = 'http://192.168.1.20:10088/UserManage/AddUser'
    data = {'json': '{"Us_id": "",'
                    ' "Us_account": "aaa",'
                    ' "Us_name": "aaaaaaa",'
                    ' "Us_type": "2",'
                    ' "Us_status": true,'
                    ' "Us_ApproveFlag": false,'
                    ' "Us_remark": "",'
                    ' "UnitID": "128",'
                    ' "Unit_name": "大龙rong区域",'
                    ' "Us_Password": "111"}'}
    r = Run_api().send_api('post', url=url, data=data)
